package weixin.service;


import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import weixin.WechatParam;
import weixin.dao.WechatDao;

@Service
public class WechatService {
	
	@Autowired
	private WechatDao wechatDao;
	private ReentrantReadWriteLock access_token_lock=new ReentrantReadWriteLock();
	private ReentrantReadWriteLock api_ticket_lock=new ReentrantReadWriteLock();
	
	public String getAccess_token(){
		access_token_lock.readLock().lock();
		String Access_token=WechatParam.getAccess_token();
		access_token_lock.readLock().unlock();//释放读锁
		return Access_token;
	}
	
	public String getApi_ticket(){
		api_ticket_lock.readLock().lock();
		String Api_ticket=WechatParam.getApi_ticket();
		api_ticket_lock.readLock().unlock();
		return Api_ticket;
	}
	public void initWechat(){
		wechatDao.initWechatParam();//1.初始化微信必要参数
		
		ScheduledThreadPoolExecutor scheduler=new ScheduledThreadPoolExecutor(2); 
		scheduler.scheduleAtFixedRate(new Runnable() {
			public void run() {
				access_token_lock.writeLock().lock();
				wechatDao.updateAccess_token();//2，更新access_token
				access_token_lock.writeLock().unlock();
			}
		}, 0, WechatParam.access_token_baseTime, TimeUnit.SECONDS);//创建一个周期性的调度，第一次调度是0， 随后每隔1800秒，更新一次
		
		scheduler.scheduleAtFixedRate(new Runnable() {
			public void run() {
				api_ticket_lock.writeLock().lock();
				wechatDao.updateApi_ticket();//3,更新jsapi_ticket
				api_ticket_lock.writeLock().unlock();
			}
		}, 0, WechatParam.api_ticket_baseTime, TimeUnit.SECONDS);//创建一个周期性的调度，第一次调度是0 ， 随后每隔1800秒，更新一次

	}
}
